package com.backend.service.rbac.impl;

import cn.hutool.core.collection.CollUtil;
import com.backend.mapper.rbac.UserRoleMapper;
import com.backend.service.rbac.UserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.exception.UserRoleException;
import com.pojo.dto.AddRoleToUserDTO;
import com.pojo.entity.UserRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {
    @Autowired
    UserRoleMapper userRoleMapper;

    @Override
    public Integer deleteRolesByUserId(Long userId) {
        return userRoleMapper.deleteByUserId(userId);
    }

    @Override
    public List<String> getRolesByUserId(Long userId) {
        List<String> roles = userRoleMapper.getRolesByUserId(userId);
        return roles;
    }

    @Override
    public Integer addRolesToUser(AddRoleToUserDTO addRoleToUserDTO) {
        Long[] roleIds = addRoleToUserDTO.getRoleIds();
        Long userId = addRoleToUserDTO.getUserId();
        Integer result = userRoleMapper.addRolesToUser(userId, roleIds);
        return result;
    }

    @Override
    @Transactional
    public Integer updateRolesToUser(AddRoleToUserDTO addRoleToUserDTO) {
        List<String> rolesByUserId = getRolesByUserId(addRoleToUserDTO.getUserId());
        if (CollUtil.isEmpty(rolesByUserId)) {
            Integer resultByAdd = addRolesToUser(addRoleToUserDTO);
            if (resultByAdd == 0) {
                throw new UserRoleException("更新操作失败");
            }
            return 1;
        }
        Integer resultByDelete = deleteRolesByUserId(addRoleToUserDTO.getUserId());
        if (resultByDelete == 0) {
            throw new UserRoleException("更新操作失败");
        }
        Integer resultByAdd = addRolesToUser(addRoleToUserDTO);
        if (resultByAdd == 0) {
            throw new UserRoleException("更新操作失败");
        }
        return 1;
    }
}